package com.hyper_yang._05_juc.chap03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程间顺序调度
 * **案例**：
 * <p>
 * 多线程之间按顺序调用，实现AA->BB->CC。三个线程启动，要求如下：
 * <p>
 * AA打印5次，BB打印10次，CC打印15次
 * <p>
 * 接着
 * <p>
 * AA打印5次，BB打印10次，CC打印15次
 * <p>
 * 。。。打印10轮
 * <p>
 * 分析实现方式：
 * 1. 有一个锁Lock，3把钥匙Condition
 * 2. 有顺序通知（切换线程），需要有标识位
 * 3. 判断标志位
 * 4. 输出线程名 + 内容
 * 5. 修改标识符，通知下一个
 */
public class ThreadOrderAccess {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    private int flag = 1;

    public void print5() {
        lock.lock();
        try {
            while (flag != 1) {
                condition1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            flag = 2;
            condition2.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void print10() {
        lock.lock();
        try {
            while (flag != 2) {
                condition2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            flag = 3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            while (flag != 3) {
                condition3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            flag = 1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {

        ThreadOrderAccess orderAccess = new ThreadOrderAccess();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                orderAccess.print5();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                orderAccess.print10();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                orderAccess.print15();
            }
        }, "C").start();
    }


}
